<template>
    <div>

        <el-upload :before-upload="beforeAvatarUpload"
            :on-remove="(uploadFile: UploadFile, uploadFiles: UploadFiles) => changeHandle(uploadFiles)"
            :on-success="(response: any, uploadFile: any, uploadFiles: UploadFiles) => changeHandle(uploadFiles)"
            v-model:file-list="fileList" class="upload-demo" :action="BASE_URL + '/upload/add'" :headers="headers"
            list-type="picture">
            <el-button type="primary">Click to upload</el-button>
            <template #tip>
                <div class="el-upload__tip">
                    jpg/png files with a size less than 500kb
                </div>
            </template>
        </el-upload>

    </div>
</template>
<script setup lang='ts'>
import { ElMessage, UploadFile, UploadFiles, UploadProps, UploadUserFile } from 'element-plus';
import { ref, reactive, watchEffect } from 'vue';

const BASE_URL = import.meta.env.VITE_BASE_URL;
const IMG_URL = import.meta.env.VITE_IMG_URL;

const headers = reactive({
    Authorization: sessionStorage.getItem('token'),
});

const fileNames = defineModel<any>();

const fileList = ref<UploadUserFile[]>([]);

watchEffect(() => {


    fileList.value = fileNames.value.map((item: any) => ({url: IMG_URL + item.url, fileName: item.url }));
});

const changeHandle: any = (uploadFiles: UploadFiles) => {

 
    
    fileNames.value = uploadFiles.map((item: any) => ({url: item?.response?.data ? item.response.data : item.fileName }))

}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {

    const rawFiles = ['image/jpeg', 'image/gif', 'image/jpg', 'image/png', 'image/bmp']
    if (!rawFiles.includes(rawFile.type)) {
        ElMessage.error('请上传图片文件!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 1) {
        ElMessage.error('上传的文件不能大于1MB!')
        return false
    }
    return true
}
</script>
<style scoped lang='less'></style>